var logger = require('../../lib/logger.lib');
var sha1 = require('../services/sha1.service');
var usersService = require('../services/users.service');
var pagesService = require('../services/pages.service');//查询单页信息渲染
var siteInfoService = require('../services/site-info.service');
var categoriesService = require('../services/categories.service');
var async = require('async');
var util = require('util');
var md5 = require("md5");
var https = require("https");
var moment = require("moment");
const SMSClient = require('@alicloud/sms-sdk');
const accessKeyId = 'LTAILWAg1b7wLRp7';
const secretAccessKey = 'EFOU0NbVSzOvuzan9IE4sMlI4n2UG2';
let smsClient = new SMSClient({accessKeyId, secretAccessKey});
var vCode = "123456";

function rand(min, max)
{   
	var range = max - min;   
	var rand = Math.random();   
	return(min + Math.round(rand * range));   
}

function genVCode()
{
	return util.format("%s%s%s%s%s%s",
		rand(0, 9), rand(0, 9), rand(0, 9),
		rand(0, 9), rand(0, 9), rand(0, 9)
	);
}

module.exports = {
	register: function (req, res) {
		logger.system().info('提交注册申请');
		req.checkBody({
			'email': {
				notEmpty: {
					options: [true],
					errorMessage: '油箱不能为空'
				},
				isEmail: { errorMessage: '油箱格式不正确' }
			},
			'nickname': {
				notEmpty: {
					options: [true],
					errorMessage: '姓名不能为空'
				},
				isString: { errorMessage: '姓名需为字符串' }
			},
			'password': {
				notEmpty: {
					options: [true],
					errorMessage: '密码不能为空'
				},
				isLength: {
					options: [6],
					errorMessage: '密码不能小于 6 位'
				}
			},
			'vCode': {
				notEmpty: {
					options: [true],
					errorMessage: '验证码不能为空'
				}
			},
			'PhoneNumber': {
				notEmpty: {
					options: [true],
					errorMessage: '手机号不能为空'
				},
				isString: { errorMessage: '手机号格式不正确' }
			},
			'WeiXinID': {
				optional: true,
				isString: { errorMessage: 'WeiXinID 需为字符串' }
			},
			'WorkYears': {
				optional: true,
				isString: { errorMessage: 'WorkYears 需为字符串' }
			},
		});

		if (req.validationErrors()) {
			logger.system().error(__filename, '参数验证失败', req.validationErrors());
			return res.status(400).json({result:"failed", errorMsg:req.validationErrors()});
		}

		if (req.body.vCode != vCode)
		{
			var errorMsg = "验证码不正确";
			logger.system().error(errorMsg);
			return res.status(400).json({result:"failed", errorMsg:errorMsg});
		}

		var data = {
			type: 'admin',
			email: req.body.email,
			nickname: req.body.nickname,
			password: req.body.password,
			PhoneNumber: req.body.PhoneNumber,
			WeiXinID: req.body.WeiXinID,
			WorkYears: req.body.WorkYears,
			role: '59c0a13b1c92974bf0c0e068'
		};
		//console.log(data)
		usersService.save({ data: data }, function (err, user) {
			if (err) {
				logger[err.type]().error(__filename, err);
				return res.status(500).json({result:"failed", errorMsg: err});
			}
			logger.system().info('存储' + user);

			res.status(200).json({result:"succeed", user: user})
		});
	},

	sendVCode: function (req, res) {
		logger.system().info('后台发送验证码');
		var phoneNumber = req.query.PhoneNumber;
		logger.system().info(phoneNumber);

		if (phoneNumber == undefined) {
			logger.system().info('请求失败!' + 手机号为空);
			res.status(500).end()
		}

		vCode = genVCode();
		logger.system().info('验证码：' + vCode);

		//发送短信
		smsClient.sendSMS({
			PhoneNumbers: phoneNumber,
			SignName: '设计中心',
			TemplateCode: 'SMS_101085024',
			TemplateParam: util.format("{\"code\" : %s}", vCode)
		}).then(function (res) {
			let {Code}=res
			if (Code === 'OK') {
				//处理返回参数
				console.log(res)
			}
		}, function (err) {
			console.log(err)
		})
	}
}